const { contextBridge, ipcRenderer } = require('electron')

const winMinimize = function () {
    ipcRenderer.invoke('winMinimize')
}
const winMaximize = function () {
    ipcRenderer.invoke('winMaximize')
}
const winClose = function () {
    ipcRenderer.invoke('winClose')
}
const cartoonWatcher = function (info = { cid: 1, chapterName: '1话' }) {
    return ipcRenderer.invoke('cartoonWatcher', info)
}
const novelWatcher = function (info = { nid: 1, fileName: '1话' }) {
    return ipcRenderer.invoke('novelWatcher', info)
}
const minimize = function () {
    ipcRenderer.invoke('minimize')
}
const maximize = function () {
    ipcRenderer.invoke('maximize')
}
const close = function () {
    ipcRenderer.invoke('close')
}

const defaultSize = function () {
    ipcRenderer.invoke('defaultSize');
}
const centerWindow = function () {
    ipcRenderer.invoke('centerWindow');
}

const restart = function () {
    ipcRenderer.invoke('restart');
}

// 文件操作
const getDirPath = async function () {
    const re = await ipcRenderer.invoke('getDirPath')
    return re;
}
const getFilePath = async function (filters) {
    const re = await ipcRenderer.invoke('getFilePath', filters)
    return re;
}
const modifySetting = function (key, value) {
    ipcRenderer.invoke('modifySetting', key, value)
}
const download = function (downloadURL) {
    ipcRenderer.invoke('download', downloadURL);
}
const getUserSetting = async function () {
    return await ipcRenderer.invoke('getUserSetting');
}
const open = function (filePath) {
    ipcRenderer.invoke('open', filePath);
}
const getImagesBase64 = async function (filePath) {
    return await ipcRenderer.invoke('getImagesBase64', filePath);
}
const getArrayBuffer = async (filePath) => {
    return await ipcRenderer.invoke('getArrayBuffer', filePath);
}
const pdfConvert = async (info) => {
    return await ipcRenderer.invoke('pdfConvert', info);
}

// 通知
const receive = (channel, func) => {
    console.log(channel);
    let validChannels = [
        "updateRoute",
        "download-task-notifies",
    ]; // 白名单允许的通道  
    if (validChannels.includes(channel)) {
        ipcRenderer.on(channel, (event, ...args) => func(...args));
    } else {
        console.log(channel + " 已被拦截");
    }
}

contextBridge.exposeInMainWorld('electronApi', {
    // 测试接口
    platform: process.platform,
    // 核心窗口
    winMinimize,
    winMaximize,
    winClose,
    // 工具窗口
    cartoonWatcher,
    novelWatcher,
    // 通用功能
    minimize,
    maximize,
    close,
    // 窗口设置
    defaultSize,
    centerWindow,
    restart,
    // 文件接口
    getDirPath,
    getFilePath,
    modifySetting,
    download,
    getUserSetting,
    open,
    getImagesBase64,
    getArrayBuffer,
    pdfConvert,

    // 通知
    receive,
})